package com.chuanyang.driverh.mainhome;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chuanyang.driverh.BaseApplication;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.mainorder.GoodOwnerInfoActivity;
import com.chuanyang.driverh.responseresult.DriverInfoData;
import com.chuanyang.driverh.responseresult.OrderDetailData;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.eventbus.RefleshFragEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

public class BidOrderActivity extends BaseTitleActivity {
    private TextView tv_oredrinfo_biditem;
    private TextView tv_oredrinfo_bidtotal;
    private LinearLayout ll_oredrinfo_itemtotal;
    private TextView tv_oredrinfo_ys;
    private EditText tv_bid;
    private int totalprice;
    private double unitprice;
    private boolean isTotalPrice = false;//默认竞价的是单价
    private DriverInfoData driverinfo;
    private OrderDetailData orderDetailData;
    private TextView tv_compete;
    private TextView tv_oredrinfo_count;
    private EditText et_oredrinfo_bidmark;
    //    private String orderId;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:  //1是车队

                    bidOrder(true);

                    break;
                case 2:  //1是个人
                    bidOrder(false);
                    break;
            }
        }
    };
    private String bidId;

    @Override
    protected int getContentResId() {
        return R.layout.home_act_bidorder;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ll_oredrinfo_itemtotal = (LinearLayout) findViewById(R.id.ll_oredrinfo_itemtotal);
        tv_oredrinfo_biditem = (TextView) findViewById(R.id.tv_oredrinfo_biditem);
        tv_oredrinfo_bidtotal = (TextView) findViewById(R.id.tv_oredrinfo_bidtotal);
        tv_oredrinfo_count = (TextView) findViewById(R.id.tv_oredrinfo_count);
        tv_oredrinfo_ys = (TextView) findViewById(R.id.tv_oredrinfo_ys);
        tv_bid = (EditText) findViewById(R.id.et_oredrinfo_bid);
        et_oredrinfo_bidmark = (EditText) findViewById(R.id.et_oredrinfo_bidmark);
        tv_compete = (TextView) findViewById(R.id.tv_oredrinfo_compete);
    }

    @Override
    protected void initData() {
        orderDetailData = (OrderDetailData) (getIntent().getSerializableExtra("data"));
        driverinfo = BaseApplication.getInstance().getDriverInfo();
//        orderId = getIntent().getStringExtra("orderId");
        bidId = getIntent().getStringExtra("bidId");
       /* if (StringUtil.isBlank(orderId)) {
            requsetData(orderId);
        }*/

        setBackImg();
        getTitleTextView().setText("竞价订单");
    }

    @Override
    protected void initListener() {
        tv_compete.setOnClickListener(this);
//        ll_oredrinfo_itemtotal.setOnClickListener(this);
        et_oredrinfo_bidmark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tv_oredrinfo_count.setText(s.length() + "");
            }
        });



        /**
         * 第二种方法
         */
        tv_bid.addTextChangedListener(new TextWatcher()
        {
            public void afterTextChanged(Editable edt)
            {
                String temp = edt.toString();
                int posDot = temp.indexOf(".");
                if (posDot <= 0) return;
                if (temp.length() - posDot - 1 >2)
                {
                    edt.delete(posDot + 3, posDot + 4);
                }
            }

            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}

            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
        });

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_oredrinfo_compete:
                if (StringUtil.isBlank(tv_bid.getText().toString().trim())) {
                    PrintUtil.toast(activityContext, "请填写您的报价");
                    return;
                }
                if (Double.parseDouble(tv_bid.getText().toString().trim())<=0) {
                    PrintUtil.toast(activityContext, "请填写您的报价");
                    return;
                }

                if (isTotalPrice) {
                    totalprice = Integer.parseInt(tv_bid.getText().toString().trim());
                    unitprice = totalprice / orderDetailData.getGoodsSumWeight();

                } else {
                    unitprice = Double.parseDouble(tv_bid.getText().toString().trim());
                    totalprice = (int) (unitprice * orderDetailData.getGoodsSumWeight());

                }
                if (orderDetailData.getOrder_Amount() < totalprice) {
                    PrintUtil.toast(activityContext, "对不起 您的报价已超出货主预期价!");
                    return;
                }

                int userId = Integer.parseInt(SharedPrefUtil.getUserId());
                //如果个人是车队长且个人运力也大于订单重量  让司机选择是以个人还是车队参与竞价
                if (driverinfo.getFleet() != null && driverinfo.getFleet().getFleetLeader() == userId) {
                    if (orderDetailData.getGoodsSumWeight() <= driverinfo.getDriver().getCapacity()) //如果是车队长 个人运力大于于订单重量
                    {
                        DialogUtil.cheseCarTeamOrPersonal(this, mHandler);
                    } else {//如果是车队长 个人运力小于订单重量  只能以车队身份参与竞价
                        DialogUtil.surebidpersonal(this, mHandler, 1);
                    }
                } else {//如果不是车队长 则以个人身份参与竞价
                    bidOrder(false);
//                    DialogUtil.surebidpersonal(this, mHandler, 2);
                }
                break;
            case R.id.ll_oredrinfo_goodownerdiv:
                if (orderDetailData != null) {
                    startActivity(GoodOwnerInfoActivity.class, orderDetailData);
                }
                break;

            case R.id.ll_oredrinfo_itemtotal:
                if (isTotalPrice) {
                    isTotalPrice = false;
                    tv_oredrinfo_biditem.setTextSize(20);
                    tv_oredrinfo_bidtotal.setTextSize(15);
                    tv_oredrinfo_biditem.setTextColor(getResources().getColor(R.color.red));
                    tv_oredrinfo_bidtotal.setTextColor(getResources().getColor(R.color.gray_99));
                } else {
                    isTotalPrice = true;
                    tv_oredrinfo_biditem.setTextSize(15);
                    tv_oredrinfo_bidtotal.setTextSize(20);
                    tv_oredrinfo_biditem.setTextColor(getResources().getColor(R.color.gray_99));
                    tv_oredrinfo_bidtotal.setTextColor(getResources().getColor(R.color.red));
                }
                break;

        }
    }


    private void bidOrder(boolean isteam) {
        DialogUtil.showLoadingDialog(activityContext, "竞价...");
        if (!StringUtil.isBlank(bidId)) {//重新竞价
            Map<String, String> params = new HashMap<String, String>();
            if (!TextUtils.isEmpty(et_oredrinfo_bidmark.getText())) {
                params.put("bidRemark", et_oredrinfo_bidmark.getText().toString());
            }
            params.put("userId", SharedPrefUtil.getUserId());
            params.put("orderId", orderDetailData.getOrderId() + "");
            params.put("bidId", bidId);
            params.put("price",StringUtil.getDouble( unitprice + ""));
            params.put("bid", StringUtil.getDouble(totalprice + ""));
            if (isteam) {
                params.put("bidType", "2");//1 是个人 2是车队
            } else {
                params.put("bidType", "1");
            }
            MyHttpUtil.reBid(activityContext, params, new MyCallback<Result>(activityContext, new JsonGenericsSerializator()) {
                @Override
                public void onFail(Call call, Exception e, int id) {
                    e.printStackTrace();
                    PrintUtil.toast(activityContext, "网络异常，请稍后再试");
                }

                @Override
                public void onSuccess(Result result, int id) {
                    if (result.getCode() == ConstUtil.OK) {
                        PrintUtil.toast(activityContext, "竞价成功 请耐心等你结果！");
                        EventBus.getDefault().post(new RefleshFragEvent(0));
                        finish();
                    } else {
                        PrintUtil.toast(activityContext, result.getMsg());
                    }

                }
            });


        } else {//竞价
            Map<String, String> params = new HashMap<String, String>();
            if (!TextUtils.isEmpty(et_oredrinfo_bidmark.getText())) {
                params.put("bidRemark", et_oredrinfo_bidmark.getText().toString());

            }
            params.put("orderId", orderDetailData.getOrderId() + "");
            params.put("price", unitprice + "");
            params.put("userId", SharedPrefUtil.getUserId());
            params.put("bid", totalprice + "");
            params.put("bidStatus", "1");//1初始化 2：结束 删除
            if (isteam) {
                params.put("bidType", "2");//1 是个人 2是车队
            } else {
                params.put("bidType", "1");
            }
            MyHttpUtil.addBid(activityContext, params, new MyCallback<Result>(activityContext, new JsonGenericsSerializator()) {
                @Override
                public void onFail(Call call, Exception e, int id) {
                    e.printStackTrace();
                    PrintUtil.toast(activityContext, "网络异常，请稍后再试");
                }

                @Override
                public void onSuccess(Result result, int id) {
                    if (result.getCode() == ConstUtil.OK) {
                        PrintUtil.toast(activityContext, "竞价成功 请耐心等你结果！");
                        EventBus.getDefault().post(new RefleshFragEvent(0));
                        finish();
                    } else {
                        PrintUtil.toast(activityContext, result.getMsg());
                    }

                }
            });
        }

    }


   /* private void requsetData(String orderId) {
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderId", orderId);

        MyHttpUtil.selectOrderMsgById(activityContext, params, new MyCallback<OrderDatailResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
            }

            @Override
            public void onSuccess(OrderDatailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    orderDetailData = result.getData();
                } else {
                }
            }
        });

    }*/

}
